

#include "LedDriver.h"

enum{ALL_LEDS_ON = ~0, ALL_LEDS_OFF = ~ALL_LEDS_ON};
enum{FIRST_LED = 1, LAST_LED = 16};

static uint16_t *ledsAddress;
static uint16_t ledsImage;

static void updateHardware(void)
{
	*ledsAddress = ledsImage;
}

static bool IsOutOfBounds(int ledNumber)
{
	return (ledNumber < FIRST_LED) || (ledNumber > LAST_LED);
}

void LedDriver_Create(uint16_t * address)
{
	ledsAddress = address;
	ledsImage = ALL_LEDS_OFF;
	updateHardware();
}

static uint16_t convertLedNumberToBit(int ledNumber)
{
	return 1 << (ledNumber - 1);
}


static void setLedImageBit(int ledNumber)
{
	ledsImage |= convertLedNumberToBit(ledNumber);
}

static void clearLedImageBit(int ledNumber)
{
	ledsImage &= ~(convertLedNumberToBit(ledNumber));
}

static bool checkLedImageBit(int ledNumber)
{
	return ledsImage & (convertLedNumberToBit(ledNumber));
}

void LedDriver_TurnOn(int ledNumber)
{
	if(IsOutOfBounds(ledNumber))
		return;
		
	setLedImageBit(ledNumber);
	updateHardware();
}

void LedDriver_TurnAllOn(void)
{
	ledsImage = ALL_LEDS_ON;
	updateHardware();
}

void LedDriver_TurnOff(int ledNumber)
{
	if(IsOutOfBounds(ledNumber))
		return;
		
	clearLedImageBit(ledNumber);
	updateHardware();
}

void LedDriver_TrunAllOff(void)
{
	ledsImage = 0;
	updateHardware();
}

bool LedDriver_IsOn(int ledNumber)
{
	if(IsOutOfBounds(ledNumber))
		return false;
	else
		return checkLedImageBit(ledNumber);
}

bool LedDriver_IsOff(int ledNumber)
{
	return !LedDriver_IsOn(ledNumber);
}

void LedDriver_Destroy(void)
{

}

